package com.yyge.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyge.callback.PageCallback;
import com.yyge.vo.BeanConverter;
import com.yyge.vo.PageVo;
import com.yyge.util.FieldUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
public class BaseController {

    @Autowired
    private FieldUtil fieldUtil;

    public QueryWrapper getWrapper(Object object, QueryWrapper wrapper) throws Exception {
        //获取实体所有对应的列
        Map<String, ColumnCache> columnMap = LambdaUtils.getColumnMap(object.getClass());
        for (Field field : fieldUtil.getFieldNames(object)) {
            Class<?> Obj = object.getClass();

            if (field.getType().equals(String.class)) {
                String MethodName = "get" + (field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));

                // 获取方法
                Method method = Obj.getMethod(MethodName);
                // 调用方法
                Object result = method.invoke(object);
                String column = columnMap.get(LambdaUtils.formatKey(field.getName())).getColumn();
                wrapper.like(column, result);
            }
        }
        return wrapper;
    }

    public PageVo page(Integer page, Integer size, PageCallback callback){
      Page pageInfo = new Page<>();
      page = page==null ? 1:page;
      size = size==null ? 10:size;
      pageInfo.setCurrent(page);
      pageInfo.setSize(size);

      pageInfo = callback.doPage(pageInfo);
      PageVo pageVo = BeanConverter.MAPPER.page2vo(pageInfo);
      return pageVo;
    }
}
